package com.example.stlink.activitys.fragmentChild.activityTeaHome;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.stlink.R;
import com.example.stlink.configs.adapter.CourseChooseAdapter;
import com.example.stlink.configs.onRecyclerViewItemClickListener;
import com.example.stlink.model.constants.ModelFieldConstants;
import com.example.stlink.model.constants.UrlConstants;
import com.example.stlink.model.domain.Course;
import com.example.stlink.model.response.BaseResponse;
import com.example.stlink.model.response.data.CourseData;
import com.example.stlink.utils.httpUtils.GetUrlParamHttpUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

public class ChooseCourse extends AppCompatActivity {

    private ImageView abIvTitle;
    private RecyclerView rvCourseList;

    private List<Course> coursesData;
    private CourseChooseAdapter adapter;
    private static Handler handler;
    private static Bundle bundle;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_course);

        initView();
    }

    private void initView(){
        abIvTitle = findViewById(R.id.ab_iv_title);
        rvCourseList = findViewById(R.id.rv_course_list);

        coursesData = new ArrayList<>();
        adapter = new CourseChooseAdapter(
                ChooseCourse.this,
                R.layout.card_course_name_list,
                coursesData
        );
        LinearLayoutManager llm = new LinearLayoutManager(ChooseCourse.this);
        rvCourseList.setLayoutManager(llm);
        rvCourseList.setAdapter(adapter);

        bundle = getIntent().getExtras();
        handler = new Handler(Looper.getMainLooper()){
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                CourseData courseData = (CourseData) msg.obj;
                coursesData.addAll(courseData.getRecords());
                adapter.notifyDataSetChanged();
                System.out.println("size == " + adapter.getItemCount() + "................................");
            }
        };
        getUnfinishedCourseList();

        initPage();
    }

    private void initPage(){
        abIvTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        adapter.setOnItemClickListener(new onRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(RecyclerView parent, View view, int position) {
                bundle = getIntent().getExtras();
                int chooseCourseSelect = bundle.getInt(ModelFieldConstants.COURSE_CHOOSE_SELECT);
                Course course = coursesData.get(position);
                String courseName = course.getmCourseName();
                Long courseId = course.getmCourseId();
                bundle.putString(ModelFieldConstants.COURSE_NAME, courseName);
                bundle.putLong(ModelFieldConstants.COURSE_ID, courseId);
                if(chooseCourseSelect == 0){
                    Intent intent = new Intent();
                    intent.putExtras(bundle);
                    setResult(200,intent);
                    finish();
                }else if (chooseCourseSelect == 1){
                    bundle.putLong(ModelFieldConstants.NOW_SIGN_COURSE_ID, courseId);
                    bundle.putString(ModelFieldConstants.NOW_SIGN_COURSE_NAME, courseName);
                    Intent intent = new Intent(ChooseCourse.this, CheckCourseSign.class);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
            }

            @Override
            public void onItemLongClick(RecyclerView parent, View view, int position) { }
        });
    }

    private static void getUnfinishedCourseList(){
        new Thread(new Runnable() {
            final String urlParam = ModelFieldConstants.USER_ID + "=" + bundle.getLong(ModelFieldConstants.ID);
            final String url = UrlConstants.TEACHER_UNFINISHED + "?" + urlParam;
            @Override
            public void run() {
                new GetUrlParamHttpUtils() {
                    @Override
                    public void nextMethod(BaseResponse<Object> baseResponse) {
                        System.out.println("courseDataBaseResponse.getData() = " + baseResponse.getData() + "...............");

                        //解析数据
                        Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
                        Object obj = baseResponse.getData();
                        LinkedTreeMap<String, String> courseDataMap = null;
                        if(obj instanceof LinkedTreeMap){
                            courseDataMap = (LinkedTreeMap<String, String>) obj;
                        }
                        //将LinkedTreeMap中字段映射到CourseData类中
                        String jsonString = gson.toJson(courseDataMap);
                        CourseData<Course> courseData = gson.fromJson(jsonString, new TypeToken<CourseData<Course>>() {}.getType());

                        System.out.println("courseData = " + courseData);

                        if(courseData != null){
                            Message message = new Message();
                            message.obj = courseData;
                            handler.sendMessage(message);
                        }else{
                            System.out.println("courseData: null " + "...............................");
                        }
                    }
                    @Override
                    public void failedMethod(BaseResponse<Object> baseResponse) {

                    }
                }.getConnect(url);
            }
        }).start();
    }
}
